package com.xie.dome.searchservice.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import com.xie.dome.searchservice.util.DataBaseUtil;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * 数据源配置
 */
@Configuration
public class DatasourceConfig {

    @Value("${ds.basic.datasource.url}")
    private String urlBasic;
    @Value("${ds.basic.datasource.username}")
    private String userBasic;
    @Value("${ds.basic.datasource.password}")
    private String passwordBasic;
    @Value("${ds.basic.datasource.driver-class-name}")
    private String driverClassBasic;

    @Value("${ds.datasource.max_active}")
    private Integer maxActive;
    @Value("${ds.datasource.min_idle}")
    private Integer minIdle;
    @Value("${ds.datasource.initial_size}")
    private Integer initialSize;
    @Value("${ds.datasource.max_wait}")
    private Long maxWait;
    @Value("${ds.datasource.time_between_eviction_runs_millis}")
    private Long timeBetweenEvictionRunsMillis;
    @Value("${ds.datasource.min_evictable_idle_time_millis}")
    private Long minEvictableIdleTimeMillis;
    @Value("${ds.datasource.test_while_idle}")
    private Boolean testWhileIdle;
    @Value("${ds.datasource.test_while_idle}")
    private Boolean testOnBorrow;
    @Value("${ds.datasource.test_on_borrow}")
    private Boolean testOnReturn;

    @Bean(name = "dynamicDataSource")
    @Primary
    public DynamicDataSource dynamicDataSource() {
        DynamicDataSource dynamicDataSource = DynamicDataSource.getInstance();

        HashMap<String, Object> poolMap = new HashMap<>();
        poolMap.put("maxActive", maxActive);
        poolMap.put("minIdle", minIdle);
        poolMap.put("initialSize", initialSize);
        poolMap.put("maxWait", maxWait);
        poolMap.put("timeBetweenEvictionRunsMillis", timeBetweenEvictionRunsMillis);
        poolMap.put("minEvictableIdleTimeMillis", minEvictableIdleTimeMillis);
        poolMap.put("testWhileIdle", testWhileIdle);
        poolMap.put("testOnBorrow", testOnBorrow);
        poolMap.put("testOnReturn", testOnReturn);

        // basic数据源
        DruidDataSource dataSourceBasic = DataBaseUtil.initDataSource(driverClassBasic, urlBasic, userBasic, passwordBasic, poolMap);

        Map<Object, Object> map = new HashMap<>();
        map.put(DataBaseUtil.DB_BASIC, dataSourceBasic);

        dynamicDataSource.setTargetDataSources(map);
        // 默认数据源
        dynamicDataSource.setDefaultTargetDataSource(dataSourceBasic);
        return dynamicDataSource;
    }

    @Bean(name = "transactionManager")
    @Primary
    public DataSourceTransactionManager transactionManager() {
        return new DataSourceTransactionManager(dynamicDataSource());
    }

    @Bean(name = "sqlSessionFactory")
    @Primary
    public SqlSessionFactory sqlSessionFactory(@Qualifier("dynamicDataSource") DataSource dynamicDataSource)
            throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dynamicDataSource);
        return sessionFactory.getObject();
    }


    @Bean
    public ServletRegistrationBean druidServlet() {
        ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean();
        servletRegistrationBean.setServlet(new StatViewServlet());
        servletRegistrationBean.addUrlMappings("/druid/*");
        Map<String, String> initParameters = new HashMap<String, String>();
        // 用户名
        initParameters.put("loginUsername", "admin");
        // 密码
        initParameters.put("loginPassword", "admin");
        // 禁用HTML页面上的“Reset All”功能
        initParameters.put("resetEnable", "false");
        // IP白名单 (没有配置或者为空，则允许所有访问)
        initParameters.put("allow", "");
        servletRegistrationBean.setInitParameters(initParameters);
        return servletRegistrationBean;
    }

    @Bean
    public FilterRegistrationBean filterRegistrationBean() {
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
        filterRegistrationBean.setFilter(new WebStatFilter());
        filterRegistrationBean.addUrlPatterns("/*");
        filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
        return filterRegistrationBean;
    }

}